package com.garen.sys.filter;

import java.io.File;

import javax.servlet.ServletContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import com.garen.utils.CommonUtils;
import com.garen.utils.FileUtils;
import com.garen.utils.LoadResource;

/*
 * 打包css,js等资源，并流,文件的形式输出
 * */
@Component
public final class PackResource {
	
	private static Log log = LogFactory.getLog(PackResource.class);   
	
	public static final String DEPLOY_MODE = "DEPLOY.MODE";
		
	private String rootPath;
	
	public PackResource(){
		log.debug("实例化=" + this);
	}
	
	//资源初始化
	public void init(ServletContext sc){
		rootPath = sc.getRealPath("/");//获取根目录
		log.debug("根目录:" + rootPath);
		//根据开发模式打包js ,css
		String mode = System.getProperty(DEPLOY_MODE);
		if("1".equals(mode)) packJsCss(sc);
		else{
			sc.setAttribute("PACK_JS","loadJs.do");
			sc.setAttribute("PACK_CSS","loadCss.do");
		}
	}
	
	//js代码打包
	private void packJsCss(ServletContext sc){
		Long timestamp = System.currentTimeMillis();
		String jsFile = "temp/pack_" + timestamp + ".js";
		String cssFile = "temp/pack_" + timestamp + ".css";
		log.debug(jsFile +","+ cssFile);
		delPackJsCss(sc);//清空历史打包资源
		FileUtils.writeFile(rootPath + jsFile,loadJs());
		FileUtils.writeFile(rootPath + cssFile,loadCss());
		sc.setAttribute("PACK_JS",jsFile);
		sc.setAttribute("PACK_CSS",cssFile);
	}
		
	//删除历史打包资源
	private void delPackJsCss(ServletContext sc){
		File dir = new File(rootPath + "temp");
		if(dir.exists() == false) return;
		for(File f : dir.listFiles()){
			String name = f.getName().toLowerCase();
			String regx = "pack_\\d{13}\\.(js|css)";
			if(CommonUtils.isMatches(name,regx)) f.delete();
		}
	}
	
	
	public byte[] loadJs(){
		String bootJs = "js/boot/boot.js";
		LoadResource lr = new LoadResource(rootPath,".js");
		lr.addexFile(bootJs);
		lr.load("libjs/module");
		lr.load("libjs/core/UICore.js",LoadResource.MODULE_NO);
		lr.load("libjs/easyui");
		lr.load("libjs/userdefined");
		lr.load("js",LoadResource.MODULE_AMD);
		lr.delExFile(bootJs);
		lr.load(bootJs,LoadResource.MODULE_NO);
		return lr.toBytes();
	}
	
	public byte[] loadCss(){
		LoadResource lr = new LoadResource(rootPath,".css");
		lr.load("css/main.css");
		lr.load("css");
		return lr.toBytes();
	}
	
}
